<template>
  <div class="home-view">
    <header-view class="bg-weaher"></header-view>
    <main class="container px-40 text-white text-lg z-1">
      <!-- 搜索框部分 -->
      <div class="search">
        <input
          class="w-full focus:outline-none focus:shadow-lg"
          type="text"
          placeholder="请输入城市名称"
          v-model="inputCity"
          @input="handleInput"
        />
        <!-- 关键词搜索结果 -->
        <div v-if="isInput" class="result">
          <p
            class="bg-weather-content p-2 mt-1"
            v-if="searchcity"
            @click="toSearch(searchcity.name)"
          >
            {{ searchcity.name }}
          </p>
          <p class="bg-weather-content p-2 mt-1" v-else>没有找到你查找的城市</p>
        </div>
      </div>
      <!-- 城市列表部分 -->
      <!-- 当输入框输入内容时，城市列表隐藏,输入框失去焦点时，城市列表显示 -->
      <div
        class="text-lg city-list-box"
        :style="{ display: isInput ? 'none' : 'block' }"
      >
        <ul v-if="CityList.length" class="city-list">
          <li
            class="city-item flex justify-between"
            v-for="city in storedCity"
            :key="city.adcode"
          >
            <div
              class="city flex text-white cursor-pointer items-center w-full justify-between py-2"
            >
              <h3>{{ city.name }}</h3>
              <p>{{ city.livetemp }}度</p>
            </div>
            <div class="btn-group flex h-full gap-2">
              <button class="btn" @click="toSearch(city.name)">查看</button>
              <button class="btn" @click="removeCity(city.id)">删除</button>
            </div>
          </li>
          <!-- 在鼠标移入时显示按钮 -->
        </ul>
        <div v-else class="text-center text-white">
          暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
        </div>
      </div>
      <!-- 城市详情部分 -->
      <div>
        <h3 class="mt-10">近日天气</h3>
        <div class="box w-full rounded mt-2">
          <!-- 文字部分 -->
          <ul class="flex gap-6">
            <li
              class="flex flex-col flex-1 text-center gap-4"
              v-for="item in localforecast"
              :key="item.index"
            >
              <span>{{ item.week }}</span>
              <span>{{ item.date }}</span>
              <span>{{ item.dayweather }}</span>
              <span>风力{{ item.daypower }}级</span>
            </li>
          </ul>
          <!-- 图表部分 -->
          <div class="chart mt-6">
            <v-chart :option="option"> </v-chart>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import { debounce } from "lodash";
import { getLiveWeather } from "../api/request";
import { useLocalStore, useSearchStore } from "../stores/index";
import { mapState, mapActions } from "pinia";
import HeaderView from "@/components/HeaderView.vue";
export default {
  components: {
    HeaderView,
  },
  name: "HomeView",
  data() {
    return {
      inputCity: "",
      searchResult: "",
      isInput: false,
      option: {},
      storedCity: [],
    };
  },
  computed: {
    ...mapState(useLocalStore, ["localcity", "localweather", "localforecast"]),
    ...mapState(useSearchStore, ["CityList", "searchcity", "searchweather"]),
    daytemp() {
      return this.localforecast.map((item) => item.daytemp);
    },
    nighttemp() {
      return this.localforecast.map((item) => item.nighttemp);
    },
  },
  methods: {
    ...mapActions(useLocalStore, ["getLocalInfo"]),
    ...mapActions(useSearchStore, [
      "getSearchInfo",
      "AddCityList",
      "removeCity",
    ]),
    toSearch(e) {
      this.$router.push({
        name: "citydetail",
        params: { city: e },
      });
      this.inputCity = "";
    },
    renderChart(a, b) {
      this.option = {
        xAxis: {
          type: "category",
          show: false,
        },
        yAxis: {
          type: "value",
          show: false,
        },
        grid: {
          top: 40,
          left: 0,
          right: 0,
          bottom: 0,
        },
        series: [
          {
            name: "白天温度",
            type: "line",
            data: a,
            smooth: true,
            label: {
              color: "#fff",
              show: true,
              position: "top",
              formatter: "白{c}℃",
            },
          },
          {
            name: "夜晚温度",
            type: "line",
            data: b,
            smooth: true,
            label: {
              color: "#fff",
              show: true,
              position: "bottom",
              formatter: "晚{c}℃",
            },
          },
        ],
      };
    },
    handleInput() {
      if (this.inputCity.trim()) {
        this.isInput = true;
        this.getSearchInfo(this.inputCity);
      } else {
        this.isInput = false;
      }
    },
  },
  // 对当地数据进行数据处理
  watch: {
    localforecast: function (newVal) {
      if (newVal) {
        newVal.map((item, index) => {
          const weekMap = {
            1: "一",
            2: "二",
            3: "三",
            4: "四",
            5: "五",
            6: "六",
            7: "日",
          };
          if (index == 0) {
            item.week = "今天";
          } else if (index == 1) {
            item.week = "明天";
          } else {
            item.week = `周${weekMap[item.week]}`;
          }
          item.date = item.date.slice(5);
        });
      } else {
        console.log("没有数据");
      }
    },
  },
  async mounted() {
    await this.getLocalInfo();
    this.renderChart(this.daytemp, this.nighttemp);
    if (this.CityList) {
      this.storedCity = this.CityList;
      const promises = this.storedCity.map(async (item) => {
        const res = (await getLiveWeather(item.id)).data;
        item.livetemp = res.lives[0].temperature;
      });
      Promise.all(promises).then(() => {
        console.log("城市列表数据", this.storedCity);
      });
    }
  },
};
</script>

<style scoped>
.header-view {
  position: sticky;
  top: 0;
  z-index: 100;
}

.search {
  padding-top: 1rem;
  margin-bottom: 2rem;

  input {
    background-color: transparent;
    border-bottom: 1px solid #fff;
    padding: 8px 4px;

    &:focus {
      border: none;
    }
  }
}

.city-list {
  position: relative;

  .city-item {
    padding: 0 20px;
    margin-bottom: 10px;
    width: 100%;
    height: 100%;
    background: #004e71;
    transition: all 0.5s;

    .btn-group {
      opacity: 0;
      position: absolute;
      right: 0;

      .btn {
        display: flex;
        background-color: #eab308;
        height: 44px;
        width: 80px;
        text-align: center;
        justify-content: center;
        align-items: center;
      }
    }

    &:hover {
      width: 80%;

      .btn-group {
        opacity: 1;
      }
    }
  }
}

/* 天气框 */
.box {
  background: #004e71;
  margin-top: 20px;
  padding: 40px 40px 20px 40px;

  .chart {
    width: 100%;
    height: 160px;
    background: transparent;
  }
}
</style>
